#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 2

// typedef struct {
//   int *base;
//   int num;
// } stack;
// num ==0 empty,  num=max full, push base[num++]=x  , pop x=base[num--], length
// = n

typedef struct {
    int *base;
    int *top;
} stack;

void init_stack(stack* ps) {
    ps->base = malloc(sizeof(int) * MAX_SIZE);
    ps->top = ps->base;
}

int length(stack *ps) { return ps->top - ps->base; }
bool isempty(stack *ps) { return ps->base == ps->top ? true : false; }
bool isfull(stack *ps) { return length(ps) >= MAX_SIZE ? true : false; }

void push(stack *ps, int x) {
    if (isfull(ps) == true) {
        printf("stack is full!\n");
        return;
    }
    *(ps->top) = x;
    ps->top++;
}

int pop(stack *ps) {
    if (isempty(ps) == true)
        return -1;

    ps->top--;
    return *(ps->top);
}

void display(stack *ps) {
    int len = length(ps);
    if (len == 0)
        printf("stack is empty!\n");
    for (int i = 0; i < len; i++)
        printf("%d ", ps->base[i]);
    printf("\n");
}

int main(int argc, char const *argv[]) {

    stack st1;
    init_stack(&st1);
    push(&st1, 2);
    push(&st1, 12);

    display(&st1);

    push(&st1, 22);
    push(&st1, 1);
    display(&st1);

    printf("len : %d\n", length(&st1));

    printf("pop: %d\n", pop(&st1));
    printf("len : %d\n", length(&st1));
    printf("pop: %d\n", pop(&st1));
    printf("len : %d\n", length(&st1));
    printf("pop: %d\n", pop(&st1));
    printf("len : %d\n", length(&st1));
    printf("pop: %d\n", pop(&st1));
    printf("len : %d\n", length(&st1));

    display(&st1);

    printf("pop: %d\n", pop(&st1));

    printf("end prog\n");
    return 0;
}
